package com.yhn.shortlink.project.service.imp;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhn.shortlink.common.constant.RedisConstant;
import com.yhn.shortlink.common.entity.LinkDO;
import com.yhn.shortlink.project.dto.req.RecycleBinSaveReqDTO;
import com.yhn.shortlink.project.dto.req.ShortLinkPageReqDTO;
import com.yhn.shortlink.project.dto.resp.ShortLinkPageRespDTO;
import com.yhn.shortlink.project.mapper.LinkMapper;
import com.yhn.shortlink.project.service.RecycleBinService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**回收站管理接口层
 * @author yhn
 * @version 1.0
 * @description
 * @date 2024/8/7 14:12
 */
@Service
public class RecycleBinServiceImpl extends ServiceImpl<LinkMapper, LinkDO>
        implements RecycleBinService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 新增回收站
     * @param requestParam 新增请求
     * @return 是否成功
     */
    @Override
    public Boolean saveRecycleBin(RecycleBinSaveReqDTO requestParam) {
        LambdaQueryWrapper<LinkDO> queryWrapper = Wrappers.lambdaQuery(LinkDO.class)
                .eq(LinkDO::getFullShortUrl, requestParam.getFullShortUrl())
                .eq(LinkDO::getGid, requestParam.getGid())
                .eq(LinkDO::getDelFlag, 0)
                .eq(LinkDO::getEnableStatus, 0);
        LinkDO linkDO = LinkDO.builder()
                .enableStatus(1)
                .build();
        baseMapper.update(linkDO, queryWrapper);
        //删除缓存
        stringRedisTemplate.delete(
                String.format(RedisConstant.GOTO_SHORT_LINK_KEY, requestParam.getFullShortUrl())
        );
        return true;
    }

    @Override
    public IPage<ShortLinkPageRespDTO> pageShortLinkBin(ShortLinkPageReqDTO shortLinkPageReqDTO) {
        // 构建查询包装器，设置查询条件
        LambdaQueryWrapper<LinkDO> queryWrapper = Wrappers.lambdaQuery(LinkDO.class)
                .eq(LinkDO::getGid, shortLinkPageReqDTO.getGid()) // 根据全局唯一标识符（GID）进行查询
                .eq(LinkDO::getDelFlag, 0) // 筛选未被删除的链接（删除标志为0）
                .eq(LinkDO::getEnableStatus, 0); // 筛选禁用状态的链接（启用状态为0）

        // 执行分页查询，获取数据库中的分页结果
        IPage<LinkDO> resultPage = baseMapper.selectPage(shortLinkPageReqDTO, queryWrapper);

        // 将查询结果中的每条数据转换为ShortLinkPageRespDTO对象，然后返回
        return resultPage.convert(
                each -> {
                    ShortLinkPageRespDTO result = BeanUtil.toBean(each, ShortLinkPageRespDTO.class);
                    result.setDomain("http://" + result.getDomain());
                    return result;
                }
        );
    }
}
